<template>
  <li class="todo-item">
    <input type="checkbox" :checked="done" @change="handleChange" />
    <input
      v-if="isEditing"
      v-focus
      type="text"
      :value="content"
      @keyup.enter="handleEdit"
      @blur="handleEdit"
    />
    <span v-else @click="isEditing = true" :class="{ completed: done }">{{ content }}</span>
    <button @click="handleDelete">删除</button>
  </li>
</template>

<script setup>
import { ref } from 'vue'
const props = defineProps({
  id: {
    type: Number, // 因为使用时间戳作为id，所以这里用Number类型
    required: true,
  },
  content: {
    type: String,
    required: true,
  },
  done: {
    type: Boolean,
    required: true,
  },
})
const emit = defineEmits(['toggle', 'edit', 'del'])

// 实现一个自定义的指令. 约定: 在setup中, 如果一个变量为vFocus 就表示一个自定义的指令
// 指令都是应用于dom元素的. 可以扩展dom元素的功能.
// 指令的值是一个对象
const vFocus = {
  mounted(el) {
    // el就是应用指令的dom元素
    // console.log(el)
    el.focus()
  },
}

const isEditing = ref(false)

const handleChange = (event) => {
  emit('toggle', props.id, event.target.checked)
}
const handleEdit = (event) => {
  // 1. 切换编辑状态
  isEditing.value = false
  // 2. 触发自定义事件
  emit('edit', props.id, event.target.value)
}
const handleDelete = () => {
  emit('del', props.id)
}
</script>

<style scoped>
.todo-item {
  list-style: none;
  position: relative;
  padding-inline: 40px;
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}
.todo-item:hover {
  background-color: #ddd;
}
.todo-item span,
.todo-item input[type='text'] {
  flex: 1;
  margin: 0 10px;
}
.todo-item button {
  padding: 0 10px;
  outline: none;
  cursor: pointer;
}
.completed {
  color: red;
  text-decoration: line-through;
}
</style>
